﻿#include "AsioServer.h"
#include <boost/asio/ip/tcp.hpp>  
#include <boost/asio/spawn.hpp>   
#include <boost/asio/strand.hpp>
#include "../Log.h"
#include "Session.h"

const char LOG_NAME[] = "AsioServer";

using namespace  std;
using namespace boost::asio;

void AsioServer::LoopAccept(int port, yield_context yield)
{
	using boost::asio::ip::tcp;
	tcp::acceptor acceptor(io,
		tcp::endpoint(tcp::v4(), port));
	int CURRENT_MAX_ID = 0;
	while (true)
	{
		boost::system::error_code ec;
		++CURRENT_MAX_ID;
		Session* pSession = new Session(this,CURRENT_MAX_ID);
		acceptor.async_accept(pSession->GetSocket(), yield[ec]);
		if (ec)
			continue;
		LOG_INFOF(FMT("new client ip=%s port=%d") % pSession->GetSocket().remote_endpoint().address() % pSession->GetSocket().remote_endpoint().port());
		 
		pSession->Run();
	}
}


void AsioServer::Run(int port)
{
	using namespace boost::asio;
	spawn(io, [this, port](yield_context yield){
		LoopAccept(port, yield);
	});
	io.run();

}